package com;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.milling.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Array;
import java.nio.charset.Charset;
import java.util.*;

public class TestDb {
    private static final Logger logger = LoggerFactory.getLogger(TestDb.class);

    public static void main(String[] args) {
        System.out.println("file.encoding: " + System.getProperty("file.encoding"));
        System.out.println("sun.jnu.encoding: " + System.getProperty("sun.jnu.encoding"));
        System.out.println("Default Charset: " + Charset.defaultCharset());

        String boxDatas = "[{\"boxId\":1,\"boxType\":\"MIX\",\"drillInfos\":\"31752112D500, 02006111D500, 21002112D500, 27502112D500, 45005111D500, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , \"},{\"boxId\":2,\"boxType\":\"MIX\",\"drillInfos\":\"31752112D500, 31752112D500, 31752112D500, 31752112D500, 31752112D500, 31752112D500, , , , , 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500\"},{\"boxId\":3,\"boxType\":\"FULL\",\"drillInfos\":\"02006111D500\"},{\"boxId\":4,\"boxType\":\"FULL\",\"drillInfos\":\"02006111D500\"},{\"boxId\":5,\"boxType\":\"MIX\",\"drillInfos\":\"02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, 02006111D500, , , 21002112D500, 21002112D500, 21002112D500, 21002112D500, 21002112D500, 21002112D500, 21002112D500, , , \"},{\"boxId\":6,\"boxType\":\"MIX\",\"drillInfos\":\"27502112D500, 27502112D500, 27502112D500, 27502112D500, 27502112D500, 27502112D500, 27502112D500, 27502112D500, 27502112D500, 27502112D500, 27502112D500, 27502112D500, 27502112D500, 27502112D500, 27502112D500, 27502112D500, 27502112D500, 27502112D500, 27502112D500, 27502112D500, 27502112D500, , , , , , , , , , 45005111D500, 45005111D500, 45005111D500, 45005111D500, 45005111D500, 45005111D500, 45005111D500, 45005111D500, 45005111D500, 45005111D500, , , , , , , , , , \"},{\"boxId\":7,\"boxType\":\"EMPTY\",\"drillInfos\":\"\"},{\"boxId\":8,\"boxType\":\"EMPTY\",\"drillInfos\":\"\"},{\"boxId\":9,\"boxType\":\"EMPTY\",\"drillInfos\":\"\"},{\"boxId\":10,\"boxType\":\"EMPTY\",\"drillInfos\":\"\"},{\"boxId\":11,\"boxType\":\"EMPTY\",\"drillInfos\":\"\"},{\"boxId\":12,\"boxType\":\"EMPTY\",\"drillInfos\":\"\"},{\"boxId\":13,\"boxType\":\"EMPTY\",\"drillInfos\":\"\"},{\"boxId\":14,\"boxType\":\"EMPTY\",\"drillInfos\":\"\"},{\"boxId\":15,\"boxType\":\"EMPTY\",\"drillInfos\":\"\"},{\"boxId\":16,\"boxType\":\"EMPTY\",\"drillInfos\":\"\"}]";
        JSONArray jsonArray = JSONArray.parseArray(boxDatas);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String boxType = jsonObject.getString("boxType");
            if (boxType.equals("EMPTY")) {

            }
        }

//        String content = "02006111D500, 03001113D500, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , 02006111D500, 02006111D500, 02006111D500, 02006111D500, , , , , , , 03001113D500, 03001113D500, 03001113D500, 03001113D500, 03001113D500, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , 02006111D500, 03001113D500, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , 02006111D500, 02006111D500, 02006111D500, 02006111D500, , , , , , , 03001113D500, 03001113D500, 03001113D500, 03001113D500, 03001113D500, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ";
        String content = "31752112D500,03001115D500,04505113D500,05505112D500,06005112D500,08005112D500,11005111D500,11505112D500,12502112D500,14502112D500,21002112D500,21502112D500,24502112D500,29502112D500,31502112D500,32005112D500,35505112D500,39005111D500,08507112D500,10507112D500,14507112D500,17507112D500,17507112D500,05006111D500, , , , , , , , , , , , , , , , , , , , , , , , , , ,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500,03001115D500, , , ,04505113D500,04505113D500, , , , , , , , ,10507112D500,10507112D500,10507112D500, , , , , , , ,14507112D500,14507112D500,14507112D500,14507112D500, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,17507112D500,17507112D500, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,";
        List<Map<String, String>> configList = genConfigMap(6, content);
//        List<Map<String, String>> configList = genConfigMap(content);
        for (int i = 0; i < configList.size(); i++) {
            Map map = configList.get(i);
            Iterator it = map.entrySet().iterator();
            for (int j = 0; j < map.size(); j++) {
                String key = "Config"+(j+1);
                String value = (String)map.get(key);
                logger.info("key: {}, value: {}", key, value);
            }
//            logger.info("第{}个配置项: {}", i, map);
        }


    }

    private static List<Map<String, String>> genConfigMapII(int axles, String content) {
        logger.info("genConfigMap开始处理，axles: {}, content: {}", axles, content);

        try {
            if (content == null || content.trim().isEmpty()) {
                logger.error("配针内容为空");
                return new ArrayList<>();
            }

            List<String> list = Arrays.asList(content.split(","));
            int configItemCount = list.size(); // 配置项数量
            logger.info("分割后的列表大小: {}", configItemCount);

            // 根据配置项数量确定每个托盘最多可以配置的份数
            int maxCopiesPerTray;
            if (configItemCount <= 200) {
                maxCopiesPerTray = 4;
            } else if (configItemCount <= 400) {
                maxCopiesPerTray = 2;
            } else {
                maxCopiesPerTray = 1;
            }

            logger.info("配置项数量: {}, 每个托盘最多可配置 {} 份", configItemCount, maxCopiesPerTray);

            List<Map<String, String>> configList = new ArrayList<>();
            int remainingAxles = axles;
            int trayIndex = 0;

            // 计算需要的托盘数量
            int trayCount = (int) Math.ceil((double) axles / maxCopiesPerTray);
            logger.info("总共需要 {} 个托盘", trayCount);

            while (remainingAxles > 0) {
                Map<String, String> trayConfigMap = new HashMap<>();
                int copiesInThisTray = Math.min(remainingAxles, maxCopiesPerTray);

                logger.info("开始处理托盘 {}，包含 {} 份配置", trayIndex + 1, copiesInThisTray);

                // 当前托盘的总配置项数量
                int totalItemsInTray = configItemCount * copiesInThisTray;

                // 为当前托盘生成配置
                int globalConfigIndex = 0;
                for (int copyIndex = 0; copyIndex < copiesInThisTray; copyIndex++) {
                    // 计算当前份的起始和结束编号
                    int startNumber, endNumber;
                    if (configItemCount <= 200) {
                        startNumber = copyIndex * 200 + 1;
                        endNumber = startNumber + configItemCount - 1;
                    } else if (configItemCount <= 400) {
                        startNumber = copyIndex * 400 + 1;
                        endNumber = startNumber + configItemCount - 1;
                    } else {
                        startNumber = 1;
                        endNumber = configItemCount;
                    }

                    logger.debug("第 {} 份配置，编号范围: {}-{}", copyIndex + 1, startNumber, endNumber);

                    // 添加当前份的配置项
                    for (int itemIndex = 0; itemIndex < configItemCount; itemIndex++) {
                        String configKey = "Config" + (startNumber + itemIndex);
                        String configValue = list.get(itemIndex).trim();
                        trayConfigMap.put(configKey, configValue);
                        globalConfigIndex++;

                        logger.trace("{} = {}", configKey, configValue);

                        // 安全检查：确保不超过800个配置项
                        if (globalConfigIndex >= 800) {
                            logger.warn("托盘 {} 已达到800个配置项上限", trayIndex + 1);
                            break;
                        }
                    }

                    // 如果当前托盘已满，跳出循环
                    if (globalConfigIndex >= 800) {
                        break;
                    }
                }

                logger.info("托盘 {} 配置完成，包含 {} 个配置项", trayIndex + 1, trayConfigMap.size());
                configList.add(trayConfigMap);

                remainingAxles -= copiesInThisTray;
                trayIndex++;
            }

            logger.info("genConfigMap完成，返回 {} 个托盘配置", configList.size());
            return configList;

        } catch (Exception e) {
            logger.error("genConfigMap处理异常", e);
            throw new RuntimeException("配针配方解析失败: " + e.getMessage(), e);
        }
    }

    private static List<Map<String, String>> genConfigMap(int axles, String content) {
        logger.info("genConfigMap开始处理，axles: {}, content: {}", axles, content);

        try {
            if (content == null || content.trim().isEmpty()) {
                logger.error("配针内容为空");
                return new ArrayList<>();
            }

            List<String> list = Arrays.asList(content.split(","));
            int configItemCount = list.size();
            logger.info("分割后的列表大小: {}", configItemCount);

            // 确定每个托盘最多份数
            int maxCopiesPerTray;
            if (configItemCount <= 200) {
                maxCopiesPerTray = 4;
            } else if (configItemCount <= 400) {
                maxCopiesPerTray = 2;
            } else {
                maxCopiesPerTray = 1;
            }

            List<Map<String, String>> configList = new ArrayList<>();
            int remainingAxles = axles;
            int trayIndex = 0;

            while (remainingAxles > 0) {
                Map<String, String> configMap = new HashMap<>();
                int copiesInThisTray = Math.min(remainingAxles, maxCopiesPerTray);
                int configsAdded = 0;
                boolean trayFull = false;

                // 为当前托盘添加配置
                for (int copy = 0; copy < copiesInThisTray && !trayFull; copy++) {
                    int startNumber;
                    if (configItemCount <= 200) {
                        startNumber = copy * 200 + 1;
                    } else if (configItemCount <= 400) {
                        startNumber = copy * 400 + 1;
                    } else {
                        startNumber = 1;
                    }

                    for (int i = 0; i < configItemCount; i++) {
                        if (configsAdded >= 800) {
                            trayFull = true;
                            break;
                        }

                        String configKey = "Config" + (startNumber + i);
                        String configValue = list.get(i).trim();
                        configMap.put(configKey, configValue);
                        configsAdded++;
                    }
                }

                logger.info("托盘 {} 配置完成，包含 {} 份配置，{} 个配置项",
                        trayIndex + 1, Math.min(copiesInThisTray, configMap.size() / configItemCount), configMap.size());

                configList.add(configMap);
                remainingAxles -= copiesInThisTray;
                trayIndex++;
            }

            logger.info("genConfigMap完成，返回 {} 个托盘配置", configList.size());
            return configList;

        } catch (Exception e) {
            logger.error("genConfigMap处理异常", e);
            throw new RuntimeException("配针配方解析失败: " + e.getMessage(), e);
        }
    }

    private static List<Map<String, String>> genConfigMap(String content) {
        logger.info("genConfigMap开始处理，content: {}", content);

        try {
            if(content == null || content.trim().isEmpty()) {
                logger.error("配针内容为空");
                return new ArrayList<>();
            }

            List<String> list = Arrays.asList(content.split(","));
            logger.info("分割后的列表大小: {}", list.size());

            List<Map<String, String>> configList = new ArrayList<>();
            Map<String, String> configMap = new HashMap<>();
            int j = 0;

            for (int i = 0; i < list.size(); i++) {
                String configKey = "Config" + ((i + 1) - (800*j));
                String configValue = list.get(i).toString().trim();
                configMap.put(configKey, configValue);
                logger.debug("{} = {}", configKey, configValue);

                if (i > 0 && ((i + 1) % 800 == 0 || (i + 1 == list.size()))) {
                    j++;
                    logger.info("添加配置组 {}, 包含 {} 个配置项", j, configMap.size());
                    configList.add(new HashMap<>(configMap)); // 创建副本避免引用问题
                    configMap.clear(); // 清空以备下次使用
                }
            }

            logger.info("genConfigMap完成，返回 {} 个配置组", configList.size());
            return configList;

        } catch (Exception e) {
            logger.error("genConfigMap处理异常", e);
            throw new RuntimeException("配针配方解析失败: " + e.getMessage(), e);
        }
    }


    public static void mainA(String[] args) {
//        String drillInfo = "02006111D500";
//        String drillSize = drillInfo.substring(0, 4);
//        String drillType = drillInfo.substring(4, 5);
//        String drillGrindCount = drillInfo.substring(7, 8);
//        logger.info("钻头型号：{}，钻头类型：{}，钻头磨削次数：{}", drillSize, drillType, drillGrindCount);

        String jsonString = "{\n" +
                "\t\"boxId\": 1,\n" +
                "\t\"boxType\": \"MIX\",\n" +
                "\t\"drillInfos\": \"31752112D500, 02006111D500, 02256110D500, 02505112D500, 02756112D500, 03001114D500, 03505112D500, 04006113D500, 04505112D500, 50005112D500, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , \"\n" +
                "}";
        JSONObject jsonObject = JSONObject.parseObject(jsonString);

        // 提取顶层字段
        String boxId = jsonObject.getString("boxId");
        String boxType = jsonObject.getString("boxType");
        String drillInfos = jsonObject.getString("drillInfos");
        String[] drillInfoArray = drillInfos.split(","); // 将字符串按逗号分割成数组

        for (String drillInfo : drillInfoArray) {
            if(StringUtils.isNotEmpty(drillInfo)) {
                logger.info(drillInfo);
            }
/*
            if (drillInfo != null && !drillInfo.isEmpty()) {
                String drillSize = drillInfo.substring(0, 6);
                String drillType = drillInfo.substring(6, 8);
                String drillGrindCount = drillInfo.substring(8, 10);
            String drillGrindType = drillInfo.substring(10, 12);
            }
*/
        }
        System.out.println("boxId: " + boxId);
        System.out.println("boxType: " + boxType);
        System.out.println("drillInfos: " + drillInfos);

        // 获取 JSON 对象中的所有键

    }

}
